package com.nbx.app.zeuscmdport;


import java.nio.FloatBuffer;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import android.content.Context;
import android.view.MotionEvent;

/**
 * http://www.zeuscmd.com/tutorials/opengles/11-Depth.php
 * 
 *
 */
public class Render11 extends RenderBase {
	
	public Render11(Context context) {
		super(context);
	}

	private float triangle[] = {
			0.5f, -0.5f, 0.0f, 
			0.0f, 0.5f, 0.0f, 
			-0.5f,-0.5f, 0.0f};

	private float colors[] = {
			1.0f, 0.0f, 0.0f, 1.0f, 
			0.0f, 1.0f, 0.0f, 1.0f,
			0.0f, 0.0f, 1.0f, 1.0f};

	private FloatBuffer mTriangleBuffer;
	private FloatBuffer mColorsBuffer;
	
	private boolean depthTest = true;

	public void onSurfaceCreated(GL10 gl, EGLConfig config) {
		// preparation
		gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
		mTriangleBuffer = createFloatBuffer(triangle);
		mColorsBuffer = createFloatBuffer(colors);
		
		gl.glClearColor (0.0f, 0.0f, 0.0f, 0.0f);

		gl.glEnable(GL10.GL_DEPTH_TEST);
		gl.glDepthFunc(GL10.GL_LEQUAL);

		gl.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
		gl.glClearDepthf(1.0f);

		gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mTriangleBuffer);
		gl.glColorPointer(4, GL10.GL_FLOAT, 0, mColorsBuffer);
		gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
		gl.glEnableClientState(GL10.GL_COLOR_ARRAY);		
	}

	public void onSurfaceChanged(GL10 gl, int width, int height) {
		gl.glMatrixMode(GL10.GL_PROJECTION);
		gl.glLoadIdentity();

		gl.glViewport(0, 0, width, height);
		gl.glOrthof(-1.0f, 1.0f, -1.0f, 1.0f, -1.0f, 20.0f);

		gl.glMatrixMode(GL10.GL_MODELVIEW);
		gl.glLoadIdentity();
	}

	public void onDrawFrame(GL10 gl) {
		if(depthTest){
			gl.glEnable(GL10.GL_DEPTH_TEST);
		}else{
			gl.glDisable(GL10.GL_DEPTH_TEST);
		}
		
		gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
		gl.glLoadIdentity();

		gl.glDrawArrays(GL10.GL_TRIANGLES, 0, 3);

		gl.glPushMatrix();
		{
			gl.glTranslatef(-0.2f, 0.0f, -1.0f);
			gl.glDrawArrays(GL10.GL_TRIANGLES, 0, 3);
			gl.glRotatef(45.0f, 0.0f, 0.0f, 1.0f);
			gl.glDrawArrays(GL10.GL_TRIANGLES, 0, 3);
		}
		gl.glPopMatrix();

		gl.glPushMatrix();
		{
			gl.glTranslatef(0.5f, 0.0f, 0.0f);
			gl.glScalef(0.5f, 0.5f, 0.5f);
			gl.glDrawArrays(GL10.GL_TRIANGLES, 0, 3);
		}
		gl.glPopMatrix();
	}
	
	@Override
	public boolean handleTouchEvent(MotionEvent event) {
		if (event.getAction() == MotionEvent.ACTION_UP) {
			depthTest = !depthTest;
			return true;
		}
		return false;
	}	
}